#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2020/11/27
# @Author    :Erinyu
# @Email     :yuailing@bbdservice.com
# @File      :IC_UpaidLoanBalPro
# @Software  :PyCharm

'''eof
name:未结清贷款余额与未结清贷款合同金额占比
code:IC_UpaidLoanBalPro
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

def NaNCheck(str):
    return False if str in null_type_list else True

def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False

# 未结清贷款余额与未结清贷款合同金额占比
# Factor1 = 贷记卡账户汇总信息段(PC02H)[0.1]·最近6个月平均使用额度(PC02HJ05)[1.1]
# Factor2 = 贷记卡账户汇总信息段(PC02H)[0.1]·授信总额(PC02HJ01) [1.1] + 准贷记卡账户汇总信息段(PC02I)[0.1]·授信总额(PC02IJ01)
# factor =使用额度/授信额度
# PCO[1.1] - PC02[0.1] - (PC02H)[0.1]/(PC02I)[0.1] - (PC02HJ05)[1.1]/(PC02HJ01)[1.1]/(PC02IJ01)[1.1]
# "Factor1=二代的非循环贷账户汇总信息段(PC02E)·余额(PC02EJ02)+循环额度下分账户汇总信息段(PC02F)·余额(PC02FJ02)+循环贷账户汇总信息段(PC02G)·余额(PC02GJ02)
# Factor2 = (非循环贷账户汇总信息段(PC02E)·授信总额(PC02EJ01)+循环额度下分账户汇总信息段(PC02F)·授信总额(PC02FJ01)+循环贷账户汇总信息段(PC02G)·授信总额(PC02GJ01))
#
# Factor = Factor1 / Factor2"


def IC_UpaidLoanBalPro():
    data = IC_DSJ.get('data')
    factor1 = []
    factor2 = []
    # 信贷交易信息概要 PCO [1.1]
    PCO = getTable(data, 'PCO', 1, 0)
    if PCO == [{}]:
        return u'缺失值'
    elif PCO == 0:
        return 0
    else:
        # 信贷交易信息概要信息单元 PC02[0.1]
        PC02 = getTable(PCO[0], 'PC02', 0, 0)
        if PC02 == [{}]:
            return u'缺失值'
        elif PC02 == 0:
            return 0
        else:
            # 贷记卡账户汇总信息段 PC02H [0.1]
            PC02H = getTable(PC02[0], 'PC02H', 0, 1)
            if PC02H == [{}]:
                factor1.append(None)
                factor2.append(None)
            elif PC02H == 0:
                factor1.append(0)
                factor2.append(0)
            else:
                # 最近6个月平均使用额度 PC02HJ05 [1.1]
                PC02HJ05 = PC02H[0].get("PC02HJ05")
                if intCheck(PC02HJ05):
                    factor1.append(int(PC02HJ05))
                else:
                    factor1.append(None)
                # 授信总额 PC02HJ01 [1.1]
                PC02HJ01 = PC02H[0].get("PC02HJ01")
                if intCheck(PC02HJ01):
                    factor2.append(int(PC02HJ01))
                else:
                    factor2.append(None)
            # 准贷记卡账户汇总信息段 PC02I [0.1]
            PC02I = getTable(PC02[0], 'PC02I', 0, 1)
            if PC02I == [{}]:
                factor2.append(None)
            elif PC02I == 0:
                factor2.append(0)
            else:
                # 授信总额 PC02IJ01 [1.1]
                PC02IJ01 = PC02I[0].get("PC02IJ01")
                if intCheck(PC02IJ01):
                    factor2.append(int(PC02IJ01))
                else:
                    factor2.append(None)

    factor1 = [x for x in factor1 if x is not None]
    factor2 = [x for x in factor2 if x is not None]

    if len(factor1) == 0 or len(factor2) == 0:
        return u'缺失值'
    else:
        try:
            if sum(factor2) == 0 or sum(factor1) == 0:
                return 0
            else:
                return "%.2f%%" % (float(sum(factor1)) / float(sum(factor2)) * 100)
        except:
            return u'缺失值'

if __name__ == '__main__':
    file_obj = open(r'IC_DSJ.json', 'r')
    content = file_obj.read()
    IC_DSJ = json.loads(content, strict=False)
    IC_DSJ = IC_DSJ.get('IC_DSJ')
    res = IC_UpaidLoanBalPro()
    print(res)

result = IC_UpaidLoanBalPro()
